package com.voxel.sense.infomsg.utils;

import android.util.Log;

import com.ansen.http.net.HTTPCaller;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okserver.download.DownloadTask;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.net.Network;
import cyy.example.com.facotry.net.helper.NetHelper;
import cyy.example.com.facotry.share.SPEngine;

import com.voxel.sense.infomsg.App;
import com.voxel.sense.infomsg.interfaces.listener.UploadListenerImp;

import cyy.example.com.facotry.constants.CommonConstants;
import io.github.lizhangqu.coreprogress.ProgressUIListener;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.http.HTTP;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.OkUpload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.upload.UploadListener;
import com.lzy.okserver.upload.UploadTask;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ChenYiYao on 2017/12/8.
 */

public class UploadUtils {
  private static UploadUtils UTILS;
  private static int num = 0;
  public static final String SERVER = CommonConstants.Constance.API_URL + "taskManage/uploadFile";//上传地址
  public static final String SERVER1 = CommonConstants.Constance.API_URL + "user/uploadHeadImg";//上传地址

  private UploadUtils() {
  }

  public static UploadUtils getInstent() {
    if (UTILS == null) {
      synchronized (UploadUtils.class) {
        if (UTILS == null) {
          UTILS = new UploadUtils();
          OkGo.getInstance().init(Factory.app());
        }
      }
    }
    return UTILS;
  }

  public void getTaskPostUpRequest(final String type, String taskNumber, List<String> listPath, final UploadListenerImp listener) {
    if (listPath != null && listPath.size() > 0) {
      List<File> files = new ArrayList<>();
      for (int i = 0; i < listPath.size(); i++) {
        files.add(new File(listPath.get(i)));
      }

      String user_id = SPEngine.getSPEngine().getUserInfo().getUser_id();
      //这里是演示可以传递任何数据
      PostRequest<String> postRequest = OkGo.<String>post(SERVER)//
        .params("fileType", type)//
        .params("taskNumber", taskNumber)//
        .addFileParams("files", files)
        .headers("_userId", user_id)
        .isMultipart(true)
        .converter(new StringConvert());

      UploadTask<String> task = OkUpload.getInstance().request(taskNumber, postRequest)
        .extra1(type)
        .register(new UploadListener<String>(taskNumber) {
          @Override
          public void onStart(Progress progress) {

            if (listener != null)
              listener.onStart(progress);
          }

          @Override
          public void onProgress(Progress progress) {
            if (listener != null)
              listener.onProgress(progress);
          }

          @Override
          public void onError(Progress progress) {

            if (listener != null)
              listener.onError(progress);
          }

          @Override
          public void onFinish(String entity, Progress progress) {
            if (listener != null)
              listener.onFinish(entity, progress);
          }

          @Override
          public void onRemove(Progress progress) {
            if (listener != null)
              listener.onRemove(progress);
          }
        }).save();
      if (listener != null) {
        listener.setTask(task);
      }
      //开始下载
      task.restart();
    }
  }

  public void getPortraitPostUpRequest(String listPath, final UploadListenerImp listener) {

    //这里是演示可以传递任何数据
    PostRequest<String> postRequest = OkGo.<String>post(SERVER1)//
      .params("userId", SPEngine.getSPEngine().getUserInfo().getUser_id())//
      .params("file", new File(listPath))//
      .isMultipart(true)
      .converter(new StringConvert());

    UploadTask<String> task = OkUpload.getInstance().request(listPath + System.currentTimeMillis(), postRequest)
      .register(new UploadListener<String>(listPath) {
        @Override
        public void onStart(Progress progress) {

          if (listener != null)
            listener.onStart(progress);
        }

        @Override
        public void onProgress(Progress progress) {
          if (listener != null)
            listener.onProgress(progress);
        }

        @Override
        public void onError(Progress progress) {

          if (listener != null)
            listener.onError(progress);
        }

        @Override
        public void onFinish(String entity, Progress progress) {
          if (listener != null)
            listener.onFinish(entity, progress);
        }

        @Override
        public void onRemove(Progress progress) {

        }
      }).save();
    //开始下载
    task.restart();
    if (listener != null) {
      listener.setTask(task);
    }
  }

  public DownloadTask getPostDownRequest(final String dir, final String fileName, String url, final DownloadListener listener) {
    GetRequest<File> request = OkGo.<File>get(url);
    DownloadTask save = OkDownload.request(url, request)
      .folder(dir)
      .fileName(fileName)
      .register(listener)
      .save();
    save.restart();
    return save;

  }

  public String downloadFile(String downloadUrl, ProgressUIListener listener) {
    String saveFilePath = getSaveFilePath(downloadUrl, App.getInstance().getApplicationContext().getExternalCacheDir());
    HTTPCaller.getInstance().downloadFile(downloadUrl, saveFilePath, null, listener);
    //返回下载路径
    return saveFilePath;
  }

  public String getSaveFilePath(String fileUrl, File fileDown) {

    String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);//获取文件名称
    String newFilePath = fileDown.getAbsolutePath() + fileName;
    return newFilePath;
  }
}
